<template>
  <div class="ivu-box">
    <Breadcrumb>
      <BreadcrumbItem>机器组管理</BreadcrumbItem>
      <BreadcrumbItem>机器组列表</BreadcrumbItem>
    </Breadcrumb>
    <Form ref="formInline" :model="request" inline :style="type === 1?'':'visibility: hidden;'">
      <FormItem>
        <Input type="text" v-model="request.name" clearable placeholder="请输入机器组名"/>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="search()" style="margin-right: 10px">搜索</Button>
        <Button type="primary" @click="toRealod" v-if="request.manager_id" style="margin-right: 10px">重置</Button>
        <Button type="primary" v-hasPermission="['38']" @click="add" style="margin-right: 10px">添加机器组</Button>
        <Button v-if="showDel" v-hasPermission="['16']" style="margin-right: 10px" @click="alldel">批量删除</Button>
      </FormItem>
    </Form>
    <!-- <div class="form_box"> -->
    <div>
      <Table :columns="infoID===6?columns2:(infoID === 7?columns3:columns1)" :height="height" :loading="loading"
             :data="tableData" @on-selection-change="selectChange">
        <template slot-scope="{ row }" slot="status">
          <span class="success" v-if="row.status==='1'">启用中</span>
          <span class="error" v-if="row.status==='2'">已被禁用</span>

        </template>
        <template slot-scope="{ row }" slot="device">
          <div v-for="(item,index) in row.device" :key="index">{{ item.name }}</div>
        </template>

        <template slot-scope="{ row }" slot="operator">
          <div v-for="(item,index) in row.operator" :key="index">{{ item.username }}</div>
        </template>

        <template slot-scope="{ row }" slot="option">
          <Button type="primary" size="small" style="margin-right: 5px" v-hasPermission="['38']"
                  @click="edit(row)">启用
          </Button>
          <Button type="error" size="small" style="margin-right: 5px" v-hasPermission="['38']"
                  @click="remove(row)">删除
          </Button>
          <Button class="button" size="small" v-hasPermission="['38']" :type="row.status === 2?'success':'error' "
                  @click="setStatus(row)">
            <span v-if="row.status === 1">禁用</span>
            <span v-else>启用</span>
          </Button>
        </template>
      </Table>
    </div>

    <div style="display: flex;justify-content: center;margin-top: 24px;">
      <Page :total="page.count" :page-size="20" :page-size-opts="[20,30,40,50,100]" show-elevator show-sizer
            show-total @on-change="handleCurrentChange" @on-page-size-change="handleSizeChange"/>
    </div>
    <Modal v-model="modal1" :title="form.id ? '编辑机器组' : '添加机器组'" :loading="modalLoading" :mask-closable="false"
           @on-ok="confirm" @on-cancel="cancel">
      <Form :model="form" :label-width="110">
        <FormItem label="机器组名">
          <Input v-model="form.name" placeholder="请输入机器组名"></Input>
        </FormItem>

        <FormItem label="经理" :data-id="infoID" v-if="infoID !== 6">
          <Select placeholder="请选择" style="width: 120px;" v-model="form.manager_id" @on-change="managerChange">
            <Option :value="item.id" v-for="(item,index) in accountList" :key="index">{{ item.username }}</Option>
          </Select>
        </FormItem>


        <FormItem label="已分配机器" v-if="form.id">
          <div class="maxH72">
            <CheckboxGroup v-model="form.device_id" v-if="allocated.length>0">
              <Checkbox v-if="form.id?item.group_id === form.id:true" :label="item.id" v-for="(item,index) in allocated"
                        :key="index">{{ item.name }}
              </Checkbox>
            </CheckboxGroup>
          </div>
        </FormItem>

        <FormItem label="未分配机器" v-if="form.id">
          <div class="maxH72">
            <CheckboxGroup v-model="form.device_id" v-if="undistributed.length>0">
              <Checkbox :label="item.id" v-for="(item,index) in undistributed" :key="index">{{ item.name }}</Checkbox>
            </CheckboxGroup>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      infoID: null,
      social: ['机器1', '机器2', '机器3', '机器4'],
      width: this.$store.state.width,
      height: this.$store.state.height,
      showDel: false, //批量删除
      type: 1, //1admin 2manager 3operator
      loading: false,
      request: {
        name: '',
        page: 1,
        loading: false
      },
      showdeviceid: true,
      columns1: [{
        width: 60,
        align: "center",
        type: 'selection'
      },
        {
          title: "机器组名",
          key: "name",
          minWidth: 150,
          align: "center"
        },

        {
          title: "机器组经理",
          key: "username",
          minWidth: 150,
          align: "center"
        },

        {
          title: "操作员",
          slot: "operator",
          minWidth: 150,
          align: "center"
        },
        {
          title: "机器",
          slot: "device",
          minWidth: 150,
          align: "center"
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 150,
          align: "center"
        },
        {
          title: "创建时间",
          key: "create_time",
          minWidth: 150,
          align: "center"
        },

        {
          title: "操作",
          minWidth: 200,
          slot: "option",
          align: "center",
          fixed: 'right',
        }
      ],

      columns2: [{
        width: 60,
        align: "center",
        type: 'selection'
      },
        {
          title: "机器组名",
          key: "name",
          minWidth: 150,
          align: "center"
        },
        {
          title: "操作员",
          slot: "operator",
          minWidth: 150,
          align: "center"
        },
        {
          title: "机器",
          slot: "device",
          minWidth: 150,
          align: "center"
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 150,
          align: "center"
        },
        {
          title: "创建时间",
          key: "create_time",
          minWidth: 150,
          align: "center"
        },

        {
          title: "操作",
          minWidth: 200,
          slot: "option",
          align: "center",
          fixed: 'right',
        }
      ],


      columns3: [{
        width: 60,
        align: "center",
        type: 'selection'
      },
        {
          title: "机器组名",
          key: "name",
          minWidth: 150,
          align: "center"
        },
        {
          title: "机器",
          slot: "device",
          minWidth: 150,
          align: "center"
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 150,
          align: "center"
        },
        {
          title: "创建时间",
          key: "create_time",
          minWidth: 150,
          align: "center"
        },

        {
          title: "操作",
          minWidth: 200,
          slot: "option",
          align: "center",
          fixed: 'right',
        }
      ],

      tableData: [],
      page: {},
      modalLoading: true,
      modal1: false,
      form: {
        id: null,
        name: '',
        manager_id: '0',
        device_id: [],
      },
      selectID: [],
      accountList: [],

      allocated: [], //已分配机器
      undistributed: [], //未分配机器
      compareManager_id: null,//比较编辑时经理是否改变
    };
  },
  mounted() {
    console.log(this.$route.query)
    if (this.$route.query.manager_id) {
      this.request.manager_id = this.$route.query.manager_id
    }
    this.infoID = JSON.parse(this.astgo.getItem("ys_prj_info")).role_id;
    console.log(JSON.parse(this.astgo.getItem("ys_prj_info")).role_id)
    // 经理不显示经理
    console.log(this.columns1)
    // this.lists();
    // this.getAccount();

  },
  methods: {
    add() {
      this.cancel();
      this.modal1 = true
      this.allocated = [];
      this.undistributed = [];
      if (this.infoID === 6) {
        console.log('6')
        this.axios.post("device/getAllDev").then(res => {
          if (res.code === 1) {
            this.allocated = res.data.allocated;
            this.undistributed = res.data.undistributed;
          }
        });

      }


    },
    alldel() {
      //批量删除
      this.$Modal.confirm({
        title: "确定要删除这些机器组？",
        onOk: () => {

          this.axios.post("device/deviceGroupDel", {id: this.selectID}).then(res => {
            if (res.code === 1) {
              this.$Message.success("删除成功");
              this.lists();
            }
          });

        },
        onCancel: () => {
        }
      });


    },
    selectChange(selection) {
      console.log('选项发生改变', selection)
      this.selectID = [];
      selection.forEach(item => {
        this.selectID.push(item.id)
      })

      if (this.selectID.length > 0) {
        this.showDel = true
      } else {
        this.showDel = false
      }

      console.log(this.selectID)


    },


    toRealod() {
      this.request = {
        name: '',
        page: 1,
        loading: false
      }
      this.search();
    },
    search() {
      this.request.page = 1;
      this.lists();
    },
    handleSizeChange(val) {
      this.request.page = 1;
      this.request.limit = val;
      this.lists();
    },
    handleCurrentChange(val) {
      this.request.page = val;
      this.lists();
    },
    lists() {

      // manager_id
      // var id =  JSON.parse(this.astgo.getItem(this.Pn + "info")).role_id

      // if(id == 6){ //经理

      // }

      this.loading = true;
      this.axios.post("device/deviceGroupList", this.request).then(res => {
        if (res.code === 1) {
          this.loading = false;
          this.tableData = res.data.list;
          this.page.count = res.data.count; // 总条数
          this.page.curPage = res.data.curPage; // 当前页
          this.page.countPage = res.data.countPage; // 总页数
        }
      });
    },
    edit(row) {
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.device_id = [];

      if (this.infoID != 6) {
        this.form.manager_id = row.manager_id;
        this.compareManager_id = row.manager_id; //比较编辑时经理是否改变

        if (this.form.manager_id && this.form.manager_id != '0') {
          this.getAllDev(row.manager_id)
        }


      } else {
        this.getAllDev()
      }


      var arr = row.device;
      var arr2 = [];

      // for(var i = 0,len=arr.length;i<len;i++){
      // 	arr2.push(arr[i].device_id)
      // }
      // this.form.device_id = arr2;

      console.log(this.form)


      this.modal1 = true;
    },
    confirm() {
      var url = this.form.id ? 'device/deviceGroupEdit' : 'device/addDeviceGroup';
      var form = this.form;
      if (form.device_id.length === 0) {
        if (form.id != this.compareManager_id) {
          form.device_id = ['b']
        } else {
          form.device_id = ['a']
        }

      }

      console.log(form)
      // this.modalLoading = false;
      // return
      this.axios.post(url, form).then(res => {
        if (res.code === 1) {
          this.modal1 = false;
          this.$Message.success("保存成功！");
          this.cancel();
          this.lists();

        } else {
          this.modal1 = false;
          this.modalLoading = false;
          this.cancel();
        }
      });


    },
    remove(row) {
      this.$Modal.confirm({
        title: '确定要删除机器组:“' + row.name + '”吗？',
        onOk: () => {

          this.axios.post("device/deviceGroupDel", {id: [row.id]}).then(res => {
            if (res.code === 1) {
              this.$Message.success("删除成功");
              this.lists();
            }
          });

        },
        onCancel: () => {
        }
      });
    },
    setStatus(row) {
      var text = "确定要" + (row.status === 2 ? "启用" : "禁用") + "机器组:“" + row.name + "”吗？";
      this.$Modal.confirm({
        title: text,
        onOk: () => {
          this.axios.post("device/deviceGroupLStatus", {id: row.id}).then(res => {
            if (res.code === 1) {
              this.$Message.success("操作成功");
              this.lists();
            }
          });
        },
        onCancel: () => {
        }
      });
    },
    cancel() {
      this.form.id = null;
      this.form.name = '';
      this.form.manager_id = '0';
      this.form.device_id = [];
      this.undistributed = [];
      this.allocated = [];

      console.log('cancel', this.form);
      console.log('cancel', this.undistributed);

    },
    getAccount() { //获取所有经理
      this.axios.post("device/getAccount", {loading: false}).then(res => {
        if (res.code === 1) {
          this.accountList = res.data;
        }
      });
    },
    getAllDev(id) { //已分配机器 未分配机器


      this.axios.post("device/getAllDev", {manager_id: id}).then(res => {
        if (res.code === 1) {
          this.form.device_id = [];
          this.allocated = res.data.allocated;

          console.log(this.allocated)

          for (var i = 0, len = this.allocated.length; i < len; i++) {
            if (this.allocated[i].group_id === this.form.id) {
              this.form.device_id.push(this.allocated[i].id)
            }

          }
          this.undistributed = res.data.undistributed;
        }
      });
    },
    managerChange(e) {
      // console.log(e)
      // this.getAllDev(e)
      console.log('managerChange', this.form.manager_id);

      this.form.device_id = [];
      this.showdeviceid = false;

      if (this.form.manager_id) {
        this.axios.post("device/getAllDev", {manager_id: this.form.manager_id}).then(res => {
          if (res.code === 1) {
            // this.form.device_id = [];
            this.allocated = res.data.allocated;

            for (var i = 0, len = this.allocated.length; i < len; i++) {
              if (this.allocated[i].group_id === this.form.id) {
                this.form.device_id.push(this.allocated[i].id)
              }
            }

            this.undistributed = res.data.undistributed;
            this.showdeviceid = true;

          }
        });
      }


    }
  }
};
</script>

<style scoped>
.spec_item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.spec_item .input {
  width: 200px;
}

.spec_item button {
  margin-left: 10px;
}
</style>
